package com.zjlp.im.netty.handler;

import com.alibaba.fastjson.JSONObject;
import com.zjlp.im.netty.MsgWrapper;
import com.zjlp.im.netty.manager.SessionManager;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultChannelHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private Logger logger = LoggerFactory.getLogger(DefaultChannelHandler.class);

    /**
     * <strong>Please keep in mind that this method will be renamed to
     * {@code messageReceived(ChannelHandlerContext, I)} in 5.0.</strong>
     * <p>
     * Is called for each message of type {@link }.
     *
     * @param ctx the {@link io.netty.channel.ChannelHandlerContext} which this {@link io.netty.channel.SimpleChannelInboundHandler}
     *            belongs to
     * @param msg the message to handle
     * @throws Exception is thrown if an error occurred
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        SessionManager sessionManager = SessionManager.getInstance();
        System.out.println("服务器开始读取消息了");
        JSONObject msgJSON = JSONObject.parseObject(new String(ByteBufUtil.getBytes(msg), "UTF-8"));
        System.out.println("服务器读取到的内容是" + msgJSON.toJSONString());
        if (msgJSON.containsKey("type") && null != msgJSON.getInteger("type")) {
            switch (msgJSON.getInteger("type")) {
                case 1:
                    //用户登陆
                    sessionManager.addUserSession(msgJSON.getString("user"),(NioSocketChannel)ctx.channel());
                    System.out.println("欢迎" + msgJSON.getString("user") + "登陆聊天服务器！");
                    break;
                case 2:
                    sessionManager.addUserSession(msgJSON.getString("user"), (NioSocketChannel)ctx.channel());
                    break;
                case 3:
                    System.out.printf("开启器用户聊天模式");
                    //用户聊天
                    NioSocketChannel socketChannel = sessionManager.getUserSession(msgJSON.getString("to"));
                    //用户在线，转发消息
                    if (null != socketChannel) {
                        String content = msgJSON.getString("content");
                        MsgWrapper msgWrapper = wrapperMsgInfo(msgJSON.getString("to"), msgJSON.getString("user"), msgJSON.getString("content"));
                        ByteBuf responseContent = ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, JSONObject.toJSONString(msgWrapper));
                        socketChannel.writeAndFlush(responseContent);
                    } else {
                        System.out.println("转发消息失败！！");
                    }
                    break;
                default:
                    System.out.println("此种消息类型暂不处理");

            }
        } else {
            System.out.println("消息类型不正确，服务器无法处理" + msgJSON.toJSONString());
        }
    }

    /**
     * @param user
     * @param to
     * @param content
     * @return
     */
    private MsgWrapper wrapperMsgInfo(String user, String to, String content) {
        MsgWrapper msgWrapper = new MsgWrapper();
        msgWrapper.setType(3);
        msgWrapper.setUser(user);
        msgWrapper.setTo(to);
        msgWrapper.setContent(content);
        return msgWrapper;
    }
}
